import { config } from './config.js'; 

const tips = {
	1: '抱歉，出现了一个错误',
	6001005: '会员不存在'
}

const authUrl = "https://scrm.bkchina.cn/scrm-bk-jd";

class HTTP {
	request(params) {
	    return new Promise((resolve, reject) => {
	      this._request(params, resolve, reject);
	    });
	  }
	   
	_request(params, resolve, reject) {
		let url = '';
		if(params.url.indexOf(authUrl) == -1) {
			url = config.api_base_url + params.url
		} else {
			url= params.url;
		}
		jd.request({
		  url: url,
		  data: params.data,
		  method: params.method,
		  header: {
			  'content-type': params.header || 'application/json' // 默认值
		  },
		  success: (res) => {
			  // console.log(JSON.stringify(res));
			  const code = res.statusCode.toString() || res.code.toString();
			  if(code.startsWith('2') || code.startsWith('1')) {
				  resolve(res.data);
			  } else {
				  reject();
				  const error_code = res.data.error_code;
				  this._show_error(error_code);
			  }
			  
		  },
		  fail: (err) => {
			  reject();
			  this._show_error(1);
		  }
		});
	}  
	 
	_show_error(err_code) {
		if(!err_code) {
			err_code = 1;
		}
		const tip = tips[err_code];
		jd.showToast({
			title: tip?tip:tips[1],
			icon: 'none',
			duration: 3000
		});
	}
}


module.exports = {
     HTTP
};